package com.chinatechstar.component.socketio;

import com.chinatechstar.cache.redis.util.RedisUtils;
import com.corundumstudio.socketio.SocketIOServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * 这个服务有点问题，每次重启spring-boot项目的时候，这个服务不能及时关闭，
 * 关闭spring-boot项目的 web 服务后，等个几秒再启动即可，如果立即启动会报socket 端口 被占用的异常
 * TODO　暂时停用
 */
//@Component
//@Order(1)
public class NettySocketServer implements CommandLineRunner {
    @Autowired
    private SocketIOServer socketIOServer;

    @Autowired
    private RedisUtils redisUtils;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run(String... args) {
        logger.info("准备启动 SocketIo...");
        redisUtils.del("socket_client_user_session");
        redisUtils.del("socket_client_session_user");
        socketIOServer.start();
    }

    /**
     * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
     */
    @PreDestroy
    private void autoStop() {
        logger.info("准备停止 SocketIo...");
        socketIOServer.stop();
        logger.info("SocketIo 已停止");
    }
}
